/**
 * Created by zhangqi on 2015/7/21.
 * 高级搜索组件
 */
define(function(require, exports,module){
    require("./highSearch.css"); //搜索样式

    //日历控件
    require("../My97DatePicker/WdatePicker");
    var tools = require("../tools");
    //是否控件
    require("../bootstrap-switch/bootstrap-switch.css");
    require("../bootstrap-switch/bootstrap-switch");
    //var Ajax = require("js/ajax");

    //多选下拉框
    require("../dayhrDropSelect/dayhrDropMultipleSelect.css");
    var dayhrDropMultipleSelect = require("../dayhrDropSelect/dayhrDropMultipleSelect");

    //单选下拉框
    require("../dayhrDropSelect/dayhrDropSelect.css");
    var dayhrDropSelect = require("../dayhrDropSelect/dayhrDropSelect");

    require("../jquery.loading");
    require("../underscore.min");
    //var tools = require("../tools.js"); //工具库

    var HighSearch = function(){
        this.init.apply(this,arguments);
    };

    HighSearch.prototype = {
        constructor: HighSearch,
        defalutOptions:{
            oTableColumnData:undefined //表头数据
            ,oMetadata:undefined //元数据表格对象
            ,$el:undefined  //搜索骨架
        },
        init:function(options){
            this.options = $.extend({},this.defalutOptions,options);
            this.oDropSelectData = {}; //下拉数据存储
            this.infoSetId = this.options.oMetadata.options.infoSetId; //来自表格对象的infoSetId
            this._initDom();
        },
        _initDom: function(){
            var t = this;
            var $el = this.options.$el;
            var options = this.options;
            var aSearchCondition = options.oTableColumnData.searchCondition;  //高级搜索的条件字段

            //创建高级搜索的表单项
            var aFHtml = [];//搜索的各项
            var sPlaceholder = "该模块暂无搜索功能"; //搜索默认的字段提示
            var isKeywordReadonly = true; //是否关键词只读
            var sDefaultName = "";
            if(aSearchCondition && aSearchCondition.length){
                for(var i= 0,len = aSearchCondition.length;i<len;i++){
                    var conditionItem = aSearchCondition[i];
                    var _isRefreshDefault = 0; //是否是默认条件
                    var _sDefaultVal = ""; //默认值
                    //如果isDefault为1表示是默认的关键词搜索条件
                    if(conditionItem.isDefault ==1){
                        sPlaceholder = "搜索" + conditionItem.conditionContent + "，点击下拉可高级搜索";
                        sDefaultName = conditionItem.conditionId;
                        conditionItem.conditionContent = "关键词";
                        t.theConditionIdOfKeyword = conditionItem.conditionId; //关键词的conditionId
                        isKeywordReadonly = false; //如果有关键词搜索字段，解除关键词只读
                    }

                    //如果有默认条件
                    if(conditionItem.refreshDefault ==1){
                        _isRefreshDefault = 1;
                        _sDefaultVal = conditionItem.defaultValue;
                    }


                    switch (conditionItem.conditionStyle){
                        //如果是文本框
                        case "text":
                            var _sVal = ""; //文本框的默认值
                            //如果有默认条件
                            if(_isRefreshDefault == 1){
                                _sVal = _sDefaultVal;
                            }
                            var _str = '<div class="search_form_row" data-type="text" data-name="'+conditionItem.conditionId+'">'+
                                '                <label for="'+conditionItem.conditionId+'" class="search_form_left">'+conditionItem.conditionContent+'：</label>'+
                                '                <div class="search_form_right">'+
                                '                    <input type="text" style="'+(conditionItem.conditionWidth?'width:'+conditionItem.conditionWidth+'px':'')+'" class="search_text" name="'+conditionItem.conditionId+'" value="'+_sVal+'">'+
                                '                </div>'+
                                '        </div>';
                            aFHtml.push(_str);
                            break;
                        //如果是日期选择框
                        case "date":
                        case "datetime":
                        case "date_yyyy_MM_dd_HH_mm":
                        case "date_yyyy_MM_dd_HH":
                        case "date_yyyy_MM":
                        case "date_yyyy":
                            var _sTimeInput =  ""; //时间文本框
                            var _aParam = conditionItem.conditionParam.split("|");
                            var _sVal = ""; //文本框的默认值
                            //如果有默认条件
                            if(_isRefreshDefault == 1){
                                _sVal = _sDefaultVal;
                            }
                            //单日期时间
                            if(_aParam.length==1){
                                _sTimeInput = '<input type="text" name="'+conditionItem.conditionId+'" readonly class="search_text Wdate" style="'+(conditionItem.conditionWidth?'width:'+conditionItem.conditionWidth+'px':'')+'" value="'+_sVal+'">';
                            }else if(_aParam.length ==2){ // 双日期时间
                                _sTimeInput = '<input type="text" name="'+conditionItem.conditionId+'" readonly class="search_text Wdate startDate" style="'+(conditionItem.conditionWidth?'width:'+conditionItem.conditionWidth+'px':'')+'" value=""> 至 <input type="text" name="'+conditionItem.conditionId+'" readonly class="search_text Wdate endDate" style="'+(conditionItem.conditionWidth?'width:'+conditionItem.conditionWidth+'px':'')+'" value="">';
                            }
                            var _str = '<div class="search_form_row search_form_row_time" data-name="'+conditionItem.conditionId+'" data-type="datatime" data-childtype="'+conditionItem.conditionStyle+'">'+
                                '                <label for="'+conditionItem.conditionId+'" class="search_form_left">'+conditionItem.conditionContent+'：</label>'+
                                '                <div class="search_form_right">'+
                                _sTimeInput+
                                '                </div>'+
                                '        </div>';
                            aFHtml.push(_str);
                            break;
                        //多选框
                        case "checkbox":
                            var _aSelect = [];
                            var aKey = conditionItem.conditionValue.split("|");
                            var aValue = conditionItem.conditionDisplay.split("|");
                            var aDefaultValue = [];//默认条件的值,值是用单引号包裹着
                            var sDefaultValue = ""; //拼接成字符串的值
                            //如果有默认条件
                            if(_isRefreshDefault == 1){
                                aDefaultValue = _sDefaultVal.split(",");
                                sDefaultValue = _sDefaultVal;
                            }
                            if(aKey.length){
                                for(var j= 0,len2=aKey.length;j<len2;j++){
                                    var keyItem = aKey[j].replace(/\'|\"/g,"");
                                    var valueItem = aValue[j];
                                    _aSelect.push('<li data-value="'+keyItem+'" class="'+(_.indexOf(aDefaultValue,"'"+keyItem+"'") != -1?'checked':'')+'"><span class="form_like_checkbox_item"></span><label>'+valueItem+'</label></li>');
                                }
                            }
                            var _str = '<div class="search_form_row" data-type="checkbox" data-name="'+conditionItem.conditionId+'">'+
                                '                <label for="'+conditionItem.conditionId+'" class="search_form_left">'+conditionItem.conditionContent+'：</label>'+
                                '                <div class="search_form_right">'+
                                '                    <ul class="form_like_checkboxlist">'+_aSelect.join("")+'</ul><input name="'+conditionItem.conditionId+'" type="hidden" value="'+sDefaultValue+'" />'+
                                '                </div>'+
                                '        </div>';
                            aFHtml.push(_str);
                            break;
                        //单选框
                        case "radio":
                            var _aSelect = [];
                            var aKey = conditionItem.conditionValue.split("|");
                            var aValue = conditionItem.conditionDisplay.split("|");
                            var sDefaultValue = ""; //拼接成字符串的值
                            //如果有默认条件
                            if(_isRefreshDefault == 1){
                                sDefaultValue = _sDefaultVal;
                            }
                            if(aKey.length){
                                for(var j= 0,len2=aKey.length;j<len2;j++){
                                    var keyItem = aKey[j].replace(/\'|\"/g,"");
                                    var valueItem = aValue[j];
                                    _aSelect.push('<li data-value="'+keyItem+'" class="'+(sDefaultValue == "'"+keyItem+"'"?'checked':'')+'"><span class="form_like_radio_item"></span><label>'+valueItem+'</label></li>');
                                }
                            }
                            var _str = '<div class="search_form_row" data-type="radio" data-name="'+conditionItem.conditionId+'">'+
                                '                <label for="'+conditionItem.conditionId+'" class="search_form_left">'+conditionItem.conditionContent+'：</label>'+
                                '                <div class="search_form_right">'+
                                '                    <ul class="form_like_radiolist">'+_aSelect.join("")+'</ul><input name="'+conditionItem.conditionId+'" type="hidden" value="'+sDefaultValue+'" />'+
                                '                </div>'+
                                '        </div>';
                            aFHtml.push(_str);
                            break;
                        //是否框
                        case "switch":
                            var sChecked = ""; //选中状态
                            //如果有默认条件
                            if(_isRefreshDefault == 1 && _sDefaultVal == "1"){
                                sChecked = 'checked';
                            }

                            var _str = '<div class="search_form_row" data-type="switch" data-name="'+conditionItem.conditionId+'">'+
                                '                <label for="'+conditionItem.conditionId+'" class="search_form_left">'+conditionItem.conditionContent+'：</label>'+
                                '                <div class="search_form_right">'+
                                '                   <div class="switch">'+
                                '                       <input class="switch-checkbox" name="'+conditionItem.conditionId+'" type="checkbox" '+sChecked+' data-size="small" />'+
                                '                   </div>'+
                                '                </div>'+
                                '        </div>';
                            aFHtml.push(_str);
                            break;
                        //多选树下拉框
                        case "treeMultipleSelect":
                            var sName = conditionItem.conditionId;
                            t.oDropSelectData[sName] = {
                                keyValueBean:conditionItem.keyValueBean
                                ,aNodes:[]
                            };
                            var sId = (new Date()).getTime()+"id"+parseInt(Math.random()*1000);

                            //如果有默认条件
                            var aDefaultValue = conditionItem.defaultValue;
                            if(_isRefreshDefault == 1){
                                aDefaultValue = _sDefaultVal.replace(/\'|\"/g,""); //去掉字符串的引号
                            }
                            var _str = '<div class="search_form_row" data-type="treeMultipleSelect" data-name="'+conditionItem.conditionId+'">'+
                                '                <label for="'+sName+'" class="search_form_left">'+conditionItem.conditionContent+'：</label>'+
                                '                <div class="search_form_right">'+
                                '                    <div class="dayhr_drop_MulSelect" id="drop'+ sId +'" data-treedataid="'+sId+'" data-name="'+sName+'" data-value="'+aDefaultValue+'"></div>'+
                                '                </div>'+
                                '        </div>';
                            aFHtml.push(_str);
                            break;
                        default :
                        //

                    }
                }
            }

            //高级搜索按钮
            var _sSearchSubmit = '<div class="search_form_row">'+
                '                <label class="search_form_left"></label>'+
                '                <div class="search_form_right">'+
                '                    <input type="button" class="search_submit" value="搜索">'+
                '                </div>'+
                '        </div>';
            aFHtml.push(_sSearchSubmit);


            $el.addClass("mmSearch");


            //创建高级搜索的外壳
            var pgHtmls = '<div class="dayhr_search_form">'+
                '                    <input type="text" name="'+sDefaultName+'" class="table_keyword dayhr_search_form_text" placeholder="'+sPlaceholder+'" '+(isKeywordReadonly?'readonly':'')+'>'+
                '                    <div class="select_ico iconfont_dayhr_base" title="展开高级搜索">&#xe600;</div>'+
                '                    <!--高级搜索区域-->'+
                '                    <div class="dayhr_search_highSearch clearfix">'+
                aFHtml.join("")+
                '                    </div>'+
                '                    <input type="button" class="iconfont_dayhr_base dayhr_search_form_submit" value="&#xe601;"/>' +
                '                    <div class="dayhr_search_form_result"></div>'+
                '                </div>';
            t.$form = $(pgHtmls);
            $el.empty();
            $el.append(t.$form);

            //如果只有1项，说明没有高级搜索的字段
            if(t.$form.find(".search_form_row").length ==1){
                t.$form.find(".search_form_row").html("该项暂无高级搜索的功能").css({textAlign:"center",fontSize:"15px",color:"#ccc"});
            }
            t.$searchContent = t.$form.find(".dayhr_search_highSearch");
            t.renderFirstHighSearchResult(); //渲染首次的搜索默认条件显示
            t._initPlugins(); //初始化控件
        },
        _initPlugins:function(){
            var t = this;
            //日历控件
            t.$form.find(".search_form_row_time").each(function(){
                var $Wdate = $(this).find(".Wdate");
                var sDateFmt = "yyyy-MM-dd"; //默认是日期型的
                var sDateType = $(this).attr("data-childtype");
                if(sDateType == "datetime"){
                    sDateFmt = "yyyy-MM-dd HH:mm:ss";
                } //如果是时间型的
                else if(sDateType == "date_worktime"){
                    sDateFmt = "H:mm";
                }else if(sDateType == "date_yyyy_MM_dd_HH_mm"){
                    sDateFmt = "yyyy-MM-dd HH:mm";
                }else if(sDateType == "date_yyyy_MM_dd_HH"){
                    sDateFmt = "yyyy-MM-dd HH";
                }else if(sDateType == "date_yyyy_MM"){
                    sDateFmt = "yyyy-MM";
                }else if(sDateType == "date_yyyy"){
                    sDateFmt = "yyyy";
                }

                if($Wdate.val() && $Wdate.val() == "current"){
                    $Wdate.val(tools.dateFormat((new Date()),sDateFmt));
                }
                //单日历触发
                if($Wdate.length == 1){
                    $Wdate.off("focus").on("focus",function(){
                        var sCurTime=new Date();
                        var sCurYear=sCurTime.getFullYear();
                        var sCurMon=sCurTime.getMonth()+1;
                        if(t.options.oMetadata.options.infoSetId=="time_amount_list"){//假期管理搜索时间限制
                            if(sCurMon==12){
                                WdatePicker({dateFmt:sDateFmt,maxDate:(sCurYear+1)});
                            }else{
                                WdatePicker({dateFmt:sDateFmt,maxDate:sCurYear});
                            }
                        }else{
                            WdatePicker({dateFmt:sDateFmt});
                        }
                    });
                }else if($Wdate.length ==2){ //双日历触发，前后日期限制
                    $Wdate.eq(0).off("focus").on("focus",function(){
                        WdatePicker({dateFmt:sDateFmt,maxDate:$Wdate.eq(1).val()});
                    });
                    $Wdate.eq(1).off("focus").on("focus",function(){
                        WdatePicker({dateFmt:sDateFmt,minDate:$Wdate.eq(0).val()});
                    });
                }
            });

            //初始化表单是否控件
            if(t.$form.find(".switch").length){
                t.$form.find(".switch").find(".switch-checkbox").bootstrapSwitch();  //设置是否选中: $(".switch-checkbox").bootstrapSwitch("state",true);  ,获取选中的情况：$(".switch-checkbox").bootstrapSwitch("state");
            }


            //绑定事件
            t._bindEvent();
        },
        /**
         * 处理延迟表单项
         * */
         handleDelayPlugins:function(callback){
            var t = this;
            //初始化下拉tree控件
            if(t.$form.find(".dayhr_drop_MulSelect").length){
                var iIndex = 0;
                var $select = t.$form.find(".dayhr_drop_MulSelect");
                var getDropTreeData = function($elem){
                    if(iIndex >= $select.length){
                        typeof callback == "function" && callback();
                        return;
                    }
                    var sName = $elem.attr("data-name");
                    var _keyValueBean = t.oDropSelectData[sName]["keyValueBean"];
                    Ajax.ApiTools().getKeyValueData({
                        data:_keyValueBean,
                        success:function(data){
                            if(data.beans && data.beans.length){
                                var tempDrop = new dayhrDropMultipleSelect({
                                    id:$elem.attr("id"),
                                    width:180,
                                    size:"small",
                                    maxHeight:250,
                                    data:data.beans,
                                    name:sName,
                                    keyValueBean:_keyValueBean
                                });
                                tempDrop.setValue($elem.attr("data-value"));
                                t.oDropSelectData[sName]["dropMulSelect"] = tempDrop;
                            }
                            iIndex++;
                            getDropTreeData($select.eq(iIndex));
                        }
                    });
                }
                getDropTreeData($select.eq(iIndex));
            }else if(t.$form.find(".dayhr_drop_select").length){
                var iIndex = 0;
                var $select = t.$form.find(".dayhr_drop_select");
                var getDropTreeData = function($elem){
                    if(iIndex >= $select.length){
                        typeof callback == "function" && callback();
                        return;
                    }
                    var sName = $elem.attr("data-name");
                    var _keyValueBean = t.oDropSelectData[sName]["keyValueBean"];
                    Ajax.ApiTools().getKeyValueData({
                        data:_keyValueBean,
                        success:function(data){
                            if(data.beans && data.beans.length){
                                var tempDrop = new dayhrDropSelect({
                                    id:$elem.attr("id"),
                                    width:180,
                                    size:"small",
                                    maxHeight:250,
                                    data:data.beans,
                                    name:sName,
                                    keyValueBean:_keyValueBean
                                });
                                tempDrop.setValue($elem.attr("data-value"));
                                t.oDropSelectData[sName]["dropSelect"] = tempDrop;
                            }
                            iIndex++;
                            getDropTreeData($select.eq(iIndex));
                        }
                    });
                }
                getDropTreeData($select.eq(iIndex));
            }else{
                typeof callback == "function" && callback();
            }

         },
        /**
         * 绑定Dom上的事件
         * */
         _bindEvent:function(){
            var t = this;
            t.isLoaded = false; //加载状态
            var aSearchCondition = t.options.oTableColumnData.searchCondition;  //高级搜索的条件字段
            var aSearchConditionList = [];  //默认搜索条件拼装
            for(var i=0;i<aSearchCondition.length;i++){
                var itemSearch = aSearchCondition[i];
                if(itemSearch.refreshDefault == 1){ //表格刚进来的默认搜索项
                    aSearchConditionList.push({conditionId:itemSearch.conditionId,conditionValue:itemSearch.defaultValue});
                }
            }

            //点击下拉按钮事件
            t.$form.on("click",".select_ico",function(e){
                if(t.$searchContent.is(":hidden")){
                    t.$searchContent.show();
                    t.$form.find(".select_ico").attr("title","隐藏高级搜索").css({ transform: "rotate(180deg)"});
                }else{
                    t.$searchContent.hide();
                    t.$form.find(".select_ico").attr("title","展开高级搜索").css({ transform: "rotate(0deg)" });
                }

                if(!t.isLoaded){
                    //处理延迟表单项
                    t.$searchContent.loading({opacity:0.9});//添加遮罩
                    t.handleDelayPlugins(function(){
                        t.isLoaded = true; //已经加载了
                        t.$searchContent.loading({state:false});//移除遮罩
                    });
                }
                e.stopPropagation();
            });
            $(document).click(function(e){
                if(!$(e.target).closest(".dayhr_search_form").length){
                    t.$searchContent.hide();
                    t.$form.find(".select_ico").attr("title","隐藏高级搜索").css({ transform: "rotate(0deg)" });
                }
            });

            //多选框事件
            t.$form.find(".form_like_checkboxlist").on("click","li",function(){
                if($(this).hasClass("checked")){
                    $(this).removeClass("checked");
                }else{
                    $(this).addClass("checked");
                }
                var _aVal = [];
                $(this).parent().find("li").each(function(){
                    if($(this).hasClass("checked")){
                        _aVal.push("'"+$(this).attr("data-value")+"'"); //把最终的值用单引号拼接
                    }
                });
                $(this).parent().next("input[type='hidden']").val(_aVal.join(",")); //设置hidden的值代替模拟checkbox的div
            });
            //单选框事件
            t.$form.find(".form_like_radiolist").on("click","li",function(){
                if($(this).hasClass("checked")){
                    $(this).removeClass("checked");
                }else{
                    $(this).addClass("checked").siblings("li").removeClass("checked");
                }
                var _aVal = "";
                $(this).parent().find("li").each(function(){
                    if($(this).hasClass("checked")){
                        _aVal = "'"+$(this).attr("data-value")+"'";
                    }
                });
                $(this).parent().next("input[type='hidden']").val(_aVal); //设置hidden的值代替模拟checkbox的div
            });
            //关闭缓存搜索结果
            t.$form.on("click",".close",function(){
                var $parent = $(this).parent();


                //清空条件后立即搜索
                if($.isArray(t.options.oMetadata.queryData.searchConditionList)){
                    for(var i=0;i<t.options.oMetadata.queryData.searchConditionList.length;i++){
                        var oItem = t.options.oMetadata.queryData.searchConditionList[i];
                        if(oItem.conditionId == $parent.attr("data-conditionid")){
                            t.options.oMetadata.queryData.searchConditionList.splice(i,1);
                        }
                    }
                }
                $parent.remove();
                t.options.oMetadata.mmg.load(); //重载表格

                //重新初始化Dom，清空所有条件的值
                t.clearHighSearchResult({
                    conditionId:$parent.attr("data-conditionid")
                });
            });

            //执行高级搜索
            var doHighSearch = function () {
                //带上之前的插件查询数据
                var _arr = []; //搜索表单集
                //循环获取控件的取值
                t.$form.find(".search_form_row[data-type]").each(function(){
                    var _sDataType = $(this).attr("data-type"); //控件类型;
                    var _oItem = {}; //查询参数组
                    //如果是文本框
                    if(_sDataType == "text"){
                        var _val = $.trim($(this).find("input[name]").val());
                        if(_val){
                            _oItem = {
                                conditionId:$(this).find("input[name]").attr("name"),
                                conditionValue:_val,
                            };
                        }
                    }else if(_sDataType =="datatime"){ //如果是日期控件
                        var $input = $(this).find("input[type='text']");
                        if($input.length ==1 && $.trim($input.val())){
                            _oItem = {
                                conditionId:$input.attr("name"),
                                conditionValue:$.trim($input.val())
                            };
                        }else if($input.length ==2){
                            //如果只有开始日期
                            if($input.eq(0).val() && !$input.eq(1).val()){
                                _oItem = {
                                    conditionId:$input.eq(0).attr("name"),
                                    conditionValue:$input.eq(0).val() + "|2099-12-31"
                                };
                            }
                            //如果只有结束日期
                            if(!$input.eq(0).val() && $input.eq(1).val()){
                                _oItem = {
                                    conditionId:$input.eq(0).attr("name"),
                                    conditionValue:"1900-01-01|"+$input.eq(1).val()
                                };
                            }
                            //如果开始和结束日期都有
                            if($input.eq(0).val() && $input.eq(1).val()){
                                _oItem = {
                                    conditionId:$input.eq(0).attr("name"),
                                    conditionValue:$input.eq(0).val()+"|"+$input.eq(1).val()
                                };
                            }
                        }
                    }else if(_sDataType =="checkbox"){  //如果是多选框
                        var _$input = $(this).find("input[type='hidden']");
                        var _val = _$input.val();
                        var _aLabel = [];
                        $(this).find(".form_like_checkboxlist").find("li").each(function(){
                            $(this).hasClass("checked") && _aLabel.push($(this).find("label").text());
                        });
                        _val && (_oItem = {
                            conditionId:_$input.attr("name"),
                            conditionValue:_val,
                            label:_aLabel.join(",")
                        });
                    }else if(_sDataType =="radio"){  //如果是多选框
                        var _$input = $(this).find("input[type='hidden']");
                        var _val = _$input.val();
                        var _aLabel = [];
                        $(this).find(".form_like_radiolist").find("li").each(function(){
                            $(this).hasClass("checked") && _aLabel.push($(this).find("label").text());
                        });
                        _val && (_oItem = {
                            conditionId:_$input.attr("name"),
                            conditionValue:_val,
                            label:_aLabel.join(",")
                        });
                    }else if(_sDataType =="switch"){  //如果是是否控件
                        var _$input = $(this).find("input[type='checkbox']");
                        var _val = _$input.prop("checked")?"1":"0";
                        _oItem = {
                            conditionId:_$input.attr("name"),
                            conditionValue:_val,
                            label:$(this).find("label.search_form_left").text() + (_val == "1"?"是":"否")
                        }
                    }else if(_sDataType =="treeMultipleSelect"){ //多选下拉树
                        var _$input = $(this).find("input[type='hidden']");
                        if(_$input.val()){
                            var aVal = _$input.val().split(",");
                            for(var i=0;i<aVal.length;i++){
                                aVal[i] = "'" + aVal[i] +"'";
                            }
                            _oItem = {
                                conditionId:_$input.attr("name"),
                                conditionValue:aVal.join(","),
                                label:_$input.prev("input.dayhr_drop_MulSelect_input").val()
                            }
                        }
                    }


                    if(!$.isEmptyObject(_oItem)){
                        _arr.push(_oItem);
                    }
                });
                t.$searchContent.hide();
                t.$form.find(".select_ico").attr("title","隐藏高级搜索").css({ transform: "rotate(0deg)" });
                //拼接搜索条件结果显示在搜索框中
                t.setSearchBoxCache({arr:_arr,flag:true});
            }

            //立即高级搜索
            t.$form.on("click",".search_submit",function(){
                doHighSearch();
            });

            $(document).on("keyup",function (e) {
                if(e.keyCode == 13 && t.$form.find(".dayhr_search_highSearch").is(":visible")){
                    doHighSearch();
                }
            });

            //关键词输入同步
            t.$form.on("blur",".table_keyword",function(){
                t.$form.find("input[name='"+$(this).attr("name")+"']").val($.trim($(this).val()));
            });
            //聚焦高亮文本框
            t.$form.on("focus",".table_keyword",function(){
                t.$searchContent.hide();
                t.$form.find(".select_ico").attr("title","隐藏高级搜索").css({ transform: "rotate(0deg)" });
            });

            //立即普通关键词的搜索
            var doSearch = function(){
                //如果关键字表单是只读的状态说明没有关键词搜索项，就不允许执行关键词搜索
                if(t.$form.find(".table_keyword").prop("readonly")){
                    return false;
                }

                t.$searchContent.hide();
                t.$form.find(".select_ico").attr("title","隐藏高级搜索").css({ transform:"rotate(0deg)" });
                var oSearch = {};
                if(aSearchCondition && aSearchCondition.length){
                    for(var i=0;i<aSearchCondition.length;i++){
                        if(aSearchCondition[i].isDefault ==1){
                            oSearch = {
                                conditionId:aSearchCondition[i].conditionId,
                                conditionValue: $.trim(t.$form.find(".table_keyword").val()),
                                label:$.trim(t.$form.find(".table_keyword").val())
                            };
                        }
                    }
                }

                for(var i=0;i<t.options.oMetadata.queryData.searchConditionList.length;i++){
                    var oItem = t.options.oMetadata.queryData.searchConditionList[i];
                    if(oItem.conditionId == oSearch.conditionId){
                        t.options.oMetadata.queryData.searchConditionList.splice(i,1); //先删除关键词的一项
                    }
                }

                t.options.oMetadata.queryData.searchConditionList.push(oSearch); //更新关键词的一项到数据集中
                t.setSearchBoxCache({arr:t.options.oMetadata.queryData.searchConditionList,flag:true}); //显示条件tag

            };
            t.$form.on("click",".dayhr_search_form_submit",function(event){
                doSearch();
                return false;
            });
            //回车立即搜索
            t.$form.find(".table_keyword").bind("keyup",function(e){
                if(e.keyCode == 13){
                    doSearch();
                }
                e.stopPropagation();
                return false;
            });

            //当有搜索条件的时候点击文本框就弹出高级搜索下拉项
            t.$form.on("click",".dayhr_search_form_result",function (e) {
                if($(e.target).hasClass("close")){
                    return false;
                }
                t.$form.find(".select_ico").trigger("click");
            });

            t.$form.find(".dayhr_search_form_result").width($(window).width()/2);

        },
        /**
         * 设置搜索框的缓存显示，拼接搜索条件结果显示在搜索框中
         * */
        setSearchBoxCache:function(opts){
            opts = opts || {};
            var t = this;
            var arr = opts.arr;

            if(arr.length){

                t.options.oMetadata.queryData.searchConditionList = arr;

                var _aResult = [];
                for(var i=0;i<arr.length;i++){
                    if(arr[i].label){
                        _aResult.push({
                            id:arr[i].conditionId
                            ,showText:arr[i].label
                        });
                    }else{
                        if(arr[i].conditionValue != 0){
                            _aResult.push({
                                id:arr[i].conditionId
                                ,showText:arr[i].conditionValue
                            });
                        }
                    }
                }
                if(_aResult.length){
                    var aHtml = [];
                    for(var i=0;i<_aResult.length;i++){
                        aHtml.push('<div class="dayhr_search_form_result_bg" data-conditionId="'+_aResult[i].id+'" title="'+(_aResult[i].showText.replace("1900-01-01","之前").replace("2099-12-31","之后"))+'"><span>'+_aResult[i].showText+'</span><i class="close" title="清除搜索结果">x</i></div>')
                    }

                    t.$form.find(".dayhr_search_form_result").show().html(aHtml.join("").replace("1900-01-01","之前").replace("2099-12-31","之后"));
                }else{
                    t.$form.find(".dayhr_search_form_result").hide(); //隐藏显示标签
                }
            }else{
                t.$form.find(".dayhr_search_form_result").hide(); //隐藏显示标签
            }

            //如果需要重载表格数据的时候就重载
            opts.flag && t.options.oMetadata.mmg.load(); //重载核心表格
        },
        /**
         * 清空搜索条件
         * */
        clearHighSearchResult:function (opts) {
            opts = opts || {};
            var t = this;
            //清空文本框
            t.$form.find("input[type='text']:not('.dayhr_search_form_text')").each(function () {
                if($(this).attr("name") == opts.conditionId){
                    $(this).val("");
                }
            });
            //清空下拉框
            if(t.oDropSelectData && !$.isEmptyObject(t.oDropSelectData)){
                for(var i in t.oDropSelectData){
                    if(t.oDropSelectData[i]['dropMulSelect'] && t.oDropSelectData[i]['dropMulSelect'].options.name == opts.conditionId && typeof t.oDropSelectData[i]['dropMulSelect'].setValue == "function"){
                        t.oDropSelectData[i]['dropMulSelect'].setValue("");
                    }
                }
            }
            //清空复选框
            t.$form.find(".search_form_row[data-type='checkbox']").each(function () {
                if($(this).attr("data-name") == opts.conditionId){
                    $(this).find("input[type='hidden']").val("");
                    $(this).find("li").removeClass("checked");
                }
            });
            //清空单选框
            t.$form.find(".search_form_row[data-type='radio']").each(function () {
                if($(this).attr("data-name") == opts.conditionId) {
                    $(this).find("input[type='hidden']").val("");
                    $(this).find("li").removeClass("checked");
                }
            });
            //清空是否控件
            t.$form.find(".switch").find(".switch-checkbox").each(function () {
                if($(this).attr("name") == opts.conditionId){
                    $(this).bootstrapSwitch("state",false)
                }
            });

            //清空关键词
            if(t.theConditionIdOfKeyword == opts.conditionId){
                t.$form.find("input.dayhr_search_form_text").val("");
            }

        },

        resetSearch:function(){
            var t = this;
            t.clearHighSearchResult();
            t.options.oMetadata.oTableColumnData.searchCondition = [];
            t.$form.find(".dayhr_search_form_text").val("");
        },
        /**
         * 渲染首次的搜索默认条件拼装
         * */
        renderFirstHighSearchResult:function () {
            var t = this;
            var aSearchCondition = t.options.oTableColumnData.searchCondition;  //高级搜索的条件字段
            var aCache = []; //默认要显示的搜索条件

            if(aSearchCondition && aSearchCondition.length) {
                for (var i = 0, len = aSearchCondition.length; i < len; i++) {
                    var conditionItem = aSearchCondition[i];
                    //如果有默认条件
                    if(conditionItem.refreshDefault ==1){
                        var oItem = {
                            conditionId:conditionItem.conditionId,
                            conditionValue:conditionItem.defaultValue,
                            label:null
                        };

                        if(conditionItem.conditionStyle == "treeMultipleSelect"){  //如果是多选下拉框类型的组件==============================
                            var aShowValue = [];
                            var aDisplay = conditionItem.conditionDisplay.split("|");
                            var aValue = conditionItem.conditionValue.split("|");
                            var aDefaultValue = conditionItem.defaultValue.replace(/'/g,"").split(",");
                            for(var i=0;i<aDisplay.length;i++){
                                for(var j=0;j<aDefaultValue.length;j++){
                                    if(aValue[i] == aDefaultValue[j]){
                                        aShowValue.push(aDisplay[i]);
                                    }
                                }
                            }
                            oItem.label = aShowValue.join(",");
                        }else if(conditionItem.conditionStyle == "switch"){  //如果是是否组件======================================

                            if(conditionItem.defaultValue == "1"){
                                oItem.label = conditionItem.conditionContent+ "：是";
                            }else{
                                oItem.label = conditionItem.conditionContent + "：否";
                            }


                        }else if(conditionItem.conditionStyle=="checkbox"){  //如果是复选框=========================================

                            var aShowValue = [];
                            var aDisplay = conditionItem.conditionDisplay.split("|");
                            var aValue = conditionItem.conditionValue.split("|");
                            var aDefaultValue = conditionItem.defaultValue.replace(/'/g,"").split(",");
                            for(var i=0;i<aDisplay.length;i++){
                                for(var j=0;j<aDefaultValue.length;j++){
                                    if(aValue[i] == aDefaultValue[j]){
                                        aShowValue.push(aDisplay[i]);
                                    }
                                }
                            }
                            oItem.label = aShowValue.join(",");


                        }/*else if(conditionItem.conditionStyle=="date_yyyy" || conditionItem.conditionStyle=="date_yyyy_MM"){  //如果是日期组件===========================

                            var aKey =conditionItem.conditionValue && conditionItem.conditionValue.split("|");
                            var aValue =conditionItem.conditionDisplay && conditionItem.conditionDisplay.split("|");
                            var aDefaultValue=conditionItem.defaultValue;
                            if(aDefaultValue){
                                if(aKey && aKey.length){
                                    for(var j= 0,len2=aKey.length;j<len2;j++){
                                        if("'"+aKey[j]+"'"==aDefaultValue){
                                            oItem.conditionValue=aValue[j];
                                        }
                                    }
                                }else {
                                    oItem.conditionValue=aDefaultValue;
                                }
                            }

                        }*/
                        else if(conditionItem.conditionStyle && conditionItem.conditionStyle.indexOf("date") != -1){   //如果是日期组件===========================
                            var sDateFmt = "yyyy-MM-dd"; //默认是日期型的
                            var sDateType = conditionItem.conditionStyle;
                            if(sDateType == "datetime"){
                                sDateFmt = "yyyy-MM-dd HH:mm:ss";
                            } //如果是时间型的
                            else if(sDateType == "date_worktime"){
                                sDateFmt = "H:mm";
                            }else if(sDateType == "date_yyyy_MM_dd_HH_mm"){
                                sDateFmt = "yyyy-MM-dd HH:mm";
                            }else if(sDateType == "date_yyyy_MM_dd_HH"){
                                sDateFmt = "yyyy-MM-dd HH";
                            }else if(sDateType == "date_yyyy_MM"){
                                sDateFmt = "yyyy-MM";
                            }else if(sDateType == "date_yyyy"){
                                sDateFmt = "yyyy";
                            }

                            if(conditionItem.defaultValue){
                                if(conditionItem.defaultValue == "current"){
                                    oItem.conditionValue = tools.dateFormat((new Date()),sDateFmt);
                                }else if(conditionItem.defaultValue.indexOf("current-") != -1 || conditionItem.defaultValue.indexOf("current+") != -1){
                                    var oDate = new Date();
                                    var str = conditionItem.defaultValue;
                                    var sOperation = str.substr(7,1); //计算类型 是 “+” 还是 “-”
                                    str = str.substr(8);
                                    var iNum = str.match(/\d+/)[0]; //数字
                                    var iUnit = str.match(/[a-zA-Z]+/)[0]; //单位
                                    if(iUnit == "d"){
                                        if(sOperation == "+"){
                                            oDate.setDate(oDate.getDate() + parseInt(iNum));
                                        }else if(sOperation == "-"){
                                            oDate.setDate(oDate.getDate() - parseInt(iNum));
                                        }
                                    }

                                    oItem.conditionValue = tools.dateFormat(oDate,sDateFmt);
                                }
                            }


                        }


                        aCache.push(oItem);
                    }
                }

                aCache.length && t.setSearchBoxCache({arr:aCache,flag:false}); //显示默认条件的浮层
            }
        },
        /**
         * =============================华丽的分割线=============End===============================
         * */
        lastPro:undefined
    }

    module.exports = HighSearch;
});
